<template>
  <div class="grade">
    <div class="search">
      <el-row class="row">
        <el-button v-for="(item, index) in teachersInfo" :key="index" @click="showClass(item)">{{ item.className }}
        </el-button>
      </el-row>
    </div>
    <div class="table" v-if="tableData.length != 0">
      <el-table v-if="isShow" ref="multipleTable" @selection-change="handleSelectionChange" :data="tableData" border
        style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column align="center" prop="studentId" label="学号" width="100"></el-table-column>
        <el-table-column align="center" prop="className" label="班级" width="100"></el-table-column>
        <el-table-column align="center" prop="studentName" label="姓名" width="100"></el-table-column>
        <el-table-column align="center" :label="subjectName">
          <el-table-column align="center" label="展示性评价">
            <el-table-column align="center" label="学科实践50%">
              <el-table-column align="center" prop="disciplinePracticeScore" label="分数">
                <template slot-scope="scope">
                  <template v-if="scope.row.editing">
                    <el-input v-model="scope.row.disciplinePracticeScore"></el-input>
                  </template>
                  <template v-else>
                    <span v-if="scope.row.disciplinePracticeScore">{{ scope.row.disciplinePracticeScore }}</span>
                  </template>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="disciplinePracticeLev" label="等级">
                <template slot-scope="scope">
                  <span v-if="scope.row.disciplinePracticeScore">{{ calculateLevel(scope.row.disciplinePracticeScore)
                    }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" label="综合答辩50%">
              <el-table-column align="center" prop="generalAnswerScore" label="分数">
                <template slot-scope="scope">
                  <template v-if="scope.row.editing">
                    <el-input v-model="scope.row.generalAnswerScore"></el-input>
                  </template>
                  <template v-else>
                    <span v-if="scope.row.generalAnswerScore">{{ scope.row.generalAnswerScore }}</span>
                  </template>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="generalAnswerLev" label="等级">
                <template slot-scope="scope">
                  <span v-if="scope.row.generalAnswerScore">{{ calculateLevel(scope.row.generalAnswerScore) }}</span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table-column>
          <el-table-column align="center" label="学科综合">
            <el-table-column align="center" prop="subjectIntegrationScore" label="总分">
              <template slot-scope="scope">
                <span v-if="scope.row.disciplinePracticeScore && scope.row.generalAnswerScore">{{
                  subjectIntegration[scope.$index].total }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="subjectIntegrationLev" label="等级">
              <template slot-scope="scope">
                <span v-if="scope.row.disciplinePracticeScore && scope.row.generalAnswerScore">{{
                  subjectIntegration[scope.$index].level }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column align="center" label="过程性评价">
            <el-table-column align="center" prop="processEvaluation" label="等级">
              <template slot-scope="scope">
                <template v-if="scope.row.editing">
                  <el-select v-model="scope.row.processEvaluation">
                    <el-option v-for="(item, index) in gradeList" :key="index" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </template>
                <template v-else>
                  <span v-if="scope.row.processEvaluation">{{ scope.row.processEvaluation }}</span>
                </template>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.editing" @click="cancelClick(scope.row)" type="text" size="small">编辑</el-button>
            <el-button v-if="scope.row.editing" @click="handleClick(scope.row)" type="text" size="small">保存</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table v-if="!isShow" ref="multipleTable" @selection-change="handleSelectionChange" :data="tableData" border
        style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column align="center" prop="studentId" label="学号"></el-table-column>
        <el-table-column align="center" prop="className" label="班级"></el-table-column>
        <el-table-column align="center" prop="studentName" label="姓名"></el-table-column>
        <el-table-column align="center" :label="subjectName">
          <el-table-column align="center" prop="processEvaluation" label="综评等级">
            <template slot-scope="scope">
              <template v-if="scope.row.editing">
                <el-select v-model="scope.row.processEvaluation">
                  <el-option v-for="(item, index) in gradeList" :key="index" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </template>
              <template v-else>
                <span v-if="scope.row.processEvaluation">{{ scope.row.processEvaluation }}</span>
              </template>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.editing" @click="cancelClick(scope.row)" type="text" size="small">编辑</el-button>
            <el-button v-if="scope.row.editing" @click="handleClick(scope.row)" type="text" size="small">保存</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="page" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <div v-if="tableData.length != 0" class="group">
      <el-button v-if="!editFlag" @click="handleBatchEdit" type="primary">批量修改</el-button>
      <el-button v-if="editFlag" @click="handleBatchSave" type="primary">批量保存</el-button>
    </div>
  </div>
</template>

<script>
import { teachClasses, bigObject, smallObject, classStudentQuery } from '@/api/api'
export default {
  data() {
    return {
      options: [],
      multipleSelection: [],
      associateCourse: ['劳动', '音乐', '美术', '体育', '信息技术'],
      mainCourses: ['语文', '数学', '英语', '科学', '道法'],
      gradeList: [
        {
          label: "A+",
          value: "A+"
        },
        {
          label: "A",
          value: "A"
        },
        {
          label: "B",
          value: "B"
        },
        {
          label: "C",
          value: "C"
        },
        {
          label: "D",
          value: "D"
        },
      ],
      page: 1,
      pageSize: 5,
      total: 0,
      centerDialogVisible: false,
      editFlag: false,
      isShow: false,
      batchEditFlag: false,
      grade: "",
      subjectName: "体育",
      tableData: [],
      formData: {
        userId: "T001",
      },
      teachersInfo: [],

    };
  },
  // 在 Vue 实例中添加计算属性和方法
  computed: {
    // 计算学科综合分数和等级
    subjectIntegration() {
      return this.tableData.map(row => {
        const disciplineScore = Number(row.disciplinePracticeScore) || 0;
        const generalScore = Number(row.generalAnswerScore) || 0;
        const total = disciplineScore + generalScore;
        let level = '';
        if (total == 100) {
          level = 'A+';
        } else if (total >= 90) {
          level = 'A';
        } else if (total >= 80) {
          level = 'B';
        } else if (total >= 60) {
          level = 'C';
        } else {
          level = 'D';
        }
        return { studentId: row.studentId, total, level };
      });
    },
    // 计算isShow的值
    isShowComputed() {
      return this.mainCourses.includes(this.subjectName);
    }
  },
  watch: {
    isShowComputed(newVal) {
      this.isShow = newVal;
    }
  },
  created() {
    this.getTeachClasses()
  },
  mounted() {
    // 初始化时设置isShow的值
    this.isShow = this.isShowComputed;

  },

  methods: {
    init_list(data) {
      for (let i in data) {
        data[i].editing = false;
        data[i].classGrade = this.teachersInfo[0].classGrade;
        data[i].evaluator = this.teachersInfo[0].teacherName;
        data[i].subjectName = this.teachersInfo[0].subjectName;
        data[i].classId = this.teachersInfo[0].classId;
      }
      return data;
    },
    showClass(item) {
      this.classStudentQuery(item)
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      let row = {
        queryType: "A",
        page: this.page,
        count: this.pageSize,
        classId: this.teachersInfo[0].classId,
        userId: this.formData.userId,
        classGrade: this.teachersInfo[0].classGrade,
        subjectName: this.teachersInfo[0].subjectName
      }
      this.classStudentQuery(row);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      let row = {
        queryType: "A",
        page: this.page,
        count: this.pageSize,
        classId: this.teachersInfo[0].classId,
        userId: this.formData.userId,
        classGrade: this.teachersInfo[0].classGrade,
        subjectName: this.teachersInfo[0].subjectName
      }
      this.classStudentQuery(row);
    },
    async getTeachClasses() {
      const res = await teachClasses(this.formData)
      console.log(res)
      this.teachersInfo = res.data;
      this.subjectName = this.teachersInfo[0].subjectName;

    },

    async classStudentQuery(row) {
      this.tableData = [];
      let data = {
        queryType: "A",
        page: this.page,
        count: this.pageSize,
        classId: row.classId,
        userId: row.userId,
        classGrade: row.classGrade,
        subjectName: row.subjectName
      }
      const res = await classStudentQuery(data);
      console.log(res, 3333)
      this.tableData = this.init_list(res.data.objects);
      this.total = res.data.total;
      console.log(this.tableData, 44444)
    },

    async submitBigObject(data) {
      let postList = [];

      for (let i in data) {
        console.log(data[i], 9999)
        if (data[i].editing) {
          let row = {
            studentId: data[i].studentId,
            studentName: data[i].studentName,
            className: data[i].className,
            classGrade: data[i].classGrade,
            subjectName: data[i].subjectName,
            disciplinePracticeScore: data[i].disciplinePracticeScore,
            disciplinePracticeLev: data[i].disciplinePracticeLev,
            generalAnswerScore: data[i].generalAnswerScore,
            generalAnswerLev: data[i].generalAnswerLev,
            subjectIntegrationScore: data[i].subjectIntegrationScore,
            subjectIntegrationLev: data[i].subjectIntegrationLev,
            processEvaluation: data[i].processEvaluation,
            evaluator: data[i].evaluator,
          }
          postList.push(row);
        }

      }

      if (!postList) {
        this.$message({
          message: '提交数据不能为空',
          type: 'success'
        })
        return;
      }

      const res = await bigObject(postList);
      console.log(res)

      // 保存数据后立即调用 classStudentQuery 方法
      let row = {
        queryType: "A",
        page: this.page,
        count: this.pageSize,
        classId: this.teachersInfo[0].classId,
        userId: this.formData.userId,
        classGrade: this.teachersInfo[0].classGrade,
        subjectName: this.teachersInfo[0].subjectName
      }
      this.classStudentQuery(row);
    },

    // 计算学科实践和综合答辩的等级
    calculateLevel(score) {
      let level = '';
      if (score >= 50) {
        level = 'A+';
      } else if (score >= 45) {
        level = 'A';
      } else if (score >= 40) {
        level = 'B';
      } else if (score >= 30) {
        level = 'C';
      } else {
        level = 'D';
      }
      return level;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleClick(row) {
      row.disciplinePracticeLev = this.calculateLevel(row.disciplinePracticeScore);
      row.generalAnswerLev = this.calculateLevel(row.generalAnswerScore);
      const subjectIntegration = this.subjectIntegration.find(item => item.studentId === row.studentId);
      row.subjectIntegrationScore = subjectIntegration.total + "";
      row.subjectIntegrationLev = subjectIntegration.level;
      let data = []
      data.push(row);
      this.submitBigObject(data)
      row.editing = false;
      // 保存当前行的数据
      // 执行保存操作
      // ...
    },
    cancelClick(row) {
      // 取消编辑状态
      row.editing = true;
    },
    selectAllRows() {
      this.tableData.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row);
      });
    },
    handleBatchEdit() {
      if (this.multipleSelection.length > 0) {
        for (let row of this.multipleSelection) {
          row.editing = true;
        }
      } else {
        this.selectAllRows();
        for (let row of this.tableData) {
          row.editing = true;
        }

      }
      this.editFlag = true; // 隐藏批量修改按钮
    },
    handleBatchSave() {
      for (let i in this.tableData) {
        let row = this.tableData[i];
        row.generalAnswerLev = this.calculateLevel(row.generalAnswerScore);
        row.disciplinePracticeLev = this.calculateLevel(row.disciplinePracticeScore);
        const subjectIntegration = this.subjectIntegration.find(item => item.studentId === row.studentId);
        row.subjectIntegrationScore = subjectIntegration.total + "";
        row.subjectIntegrationLev = subjectIntegration.level;
      }
      setTimeout(() => {
        this.submitBigObject(this.tableData)
        // 执行批量保存操作
        let row = {
          queryType: "A",
          page: this.page,
          count: this.pageSize,
          classId: this.teachersInfo[0].classId,
          userId: this.formData.userId,
          classGrade: this.teachersInfo[0].classGrade,
          subjectName: this.teachersInfo[0].subjectName
        }
        this.classStudentQuery(row);
        this.editFlag = false; // 显示批量修改按钮

      }, 3000)

    },
  },
};
</script>
<style lang="less" scoped>
.grade {
  margin: 10px;
}

.group {
  text-align: right;
}

.search {
  padding-bottom: 10px;
}

.pagination {
  margin: 10px 0;
}
</style>
